﻿using System;
using System.Globalization;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;

namespace Medianamik.Core.Index
{
	public static class Searcher
	{
		
		public static SearchResult Search(string pValue,  Guid pNodeType ,CultureInfo pCulture)
		{
			var queryBuilder = new StringBuilder();
			queryBuilder.Append("CultureName:" + pCulture.Name.Replace("-", string.Empty) );
			queryBuilder.Append(" AND (NodeTypeId:" + pNodeType.ToString("N") );
			queryBuilder.Append(" ParentTypeIds:" + pNodeType.ToString("N") + ")" );

            var formattedValue = FormatValue(pValue);
            if (!string.IsNullOrEmpty(formattedValue))
			{
				queryBuilder.Append(" AND " + formattedValue + "");
			}

		    IndexSearcher searcher = GetIndexSearcher();
            if (searcher == null) 
            {
                return SearchResult.Empty; 
            }

            var parser = new QueryParser(IndexUtils.EngineVersion, "Content", new StandardAnalyzer(IndexUtils.EngineVersion));
			Query q = parser.Parse(queryBuilder.ToString());
		    
			try
			{
                return new SearchResult(searcher.Search(q));
			}
			finally
			{
			    searcher.Close();
			}

		}

        private static string FormatValue(string pValue)
        {
            var sanitized = QueryParser.Escape(pValue);
            var values = sanitized.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (values.Length  == 0)
            {
                return string.Empty ;
            }

            var returnValue = new StringBuilder(values[0]);
            foreach (var val in values.Skip(1))
            {
                returnValue.Append(" AND " + val);
            }
            return returnValue.ToString();
                
        }

        public static int GetDocumentCount()
        {
            var reader = default(IndexReader);
            int numDocs;
            try
            {
                reader = new Indexer().GetIndexReader();
                numDocs = reader == null 
                        ? 0 
                        : reader.NumDocs();
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return numDocs;
        }

        private static IndexSearcher GetIndexSearcher()
        {
            var reader = default(IndexReader);
            bool indexExists;
            try
            {
                reader = new Indexer().GetIndexReader();
                indexExists = reader != null;
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return !indexExists 
                 ? null 
                 : new IndexSearcher(IndexUtils.IndexDirectory, true);
        }

       
	}
}
